import { createRouter, createWebHashHistory, RouterView } from 'vue-router'
import store from '@/store'
import { h } from 'vue'
const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/home')
const TopCategory = () => import('@/views/category/index.vue')
const SubCategory = () => import('@/views/category/sub.vue')
const Goods = () => import('@/views/goods/index.vue')
const Login = () => import('@/views/login/index.vue')
const LoginCallback = () => import('@/views/login/components/callback.vue')
const Cart = () => import('@/views/cart/index.vue')
const PayCheckout = () => import('@/views/member/pay/checkout')
const Pay = () => import('@/views/member/pay/index')
const PayResult = () => import('@/views/member/pay/result')
const MemberLayout = () => import('@/views/member/Layout.vue')
const MemberHome = () => import('@/views/member/home')
const MemberOrder = () => import('@/views/member/order')
const MemberOrderDetail = () => import('@/views/member/order/detail')
// 路由规则
const routes = [
  // 一集路由布局容器
  {
    path: '/',
    component: Layout,
    children: [{
      path: '/',
      component: Home
    }, {
      path: '/category/:id',
      component: TopCategory
    }, {
      path: '/category/sub/:id',
      component: SubCategory
    }, {
      path: '/product/:id',
      component: Goods
    }, {
      path: '/cart',
      component: Cart
    }, {
      path: '/member/checkout', component: PayCheckout
    }, {
      path: '/member/pay', component: Pay
    }, {
      path: '/pay/callback', component: PayResult
    }, {
      path: '/member',
      component: MemberLayout,
      children: [{ path: '/member', component: MemberHome },
        // { path: '/member/order', component: MemberOrder },
        // { path: '/member/order/:id', component: MemberOrderDetail }
        {
          path: '/member/order',
          // 创建一个routerview容器 形成嵌套关系 激活类名
          component: { render: () => h(RouterView) },
          children: [
            { path: '', component: MemberOrder },
            { path: ':id', component: MemberOrderDetail }
          ]
        }
      ]
    }]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/login/callback',
    component: LoginCallback
  }
]

// vue2.0 new vueRouter({}) 创建路由实例
// vue3.0 createRouter({}) 创建路由实例
const router = createRouter({
  // 使用hash路由模式
  history: createWebHashHistory(),
  routes,
  // 每次切换路由的时候切到路由顶部
  scrollBehavior () {
    // vue2.0 通过x,y控制
    // vur3.0 通过left和top
    return { left: 0, top: 0 }
  }
})

// 前置导航首位
router.beforeEach((to, from, next) => {
  // 判断登录状态 需要登录路由 地址是以/member开头
  // 用户信息profile
  const { profile } = store.state.user
  if (!profile.token && to.path.startsWith('/member')) {
    return next('/login?redirectUrl=' + encodeURIComponent(to.fullPath))
  }
  next()
})
export default router
